package shopping.shiro;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.stereotype.Component;
import shopping.dao.IUserDao;
import shopping.entity.User;

@Component
public class SecurityRealm extends AuthorizingRealm {

	public static final String SESSION_USER_KEY = "shopping-";

	@Resource
	IUserDao userDao;

	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		return info;
	}

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		User userLogin = tokenToUser((UsernamePasswordToken) token);
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("userName", userLogin.getUserName());
		List<User> user = userDao.findByHqlPage(User.class, map, 0, 1);
		if(user.isEmpty())
			return null;
		Object principal = token.getPrincipal();
		return new SimpleAuthenticationInfo(principal, user.get(0).getUserPwd(), userLogin.getUserName());
	}

	private User tokenToUser(UsernamePasswordToken authcToken) {
		User user = new User ();
		user.setUserName(authcToken.getUsername());
		user.setUserPwd(String.valueOf(authcToken.getPassword()));
		return user;
	}
}
